//用户的头像、昵称、金币等数据的存储
const express = require('express');
const router = express.Router();
const db = require('../database/db');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const GlobalUtil = require('../Util/GlobalUtil');

router.use(bodyParser.json());
router.use(bodyParser.text());

//获取用户信息
router.get('/getUserInfo', (req, res) => {
    const token = req.headers.authorization;
    jwt.verify(token, process.env.SECRETKEY, (err, decoded) => {
        if (err) {
            console.error(err);
            return res.status(401).json({ message: 'Invalid token' });
        } else {
            const sql = 'SELECT * FROM userdata WHERE user_id = ?';
            db.query(sql, [decoded.user_id], (err, result) => {
                if (err) {
                    res.status(500).send("Database error");
                } else if (result.length > 0) {
                    const avatar_url = result[0].avatar_url;
                    const data = {
                        nickname: result[0].nickname,
                        avatar_url: avatar_url,
                        userID: result[0].user_id,
                        designation: JSON.parse(result[0].designation)
                    }
                    res.send(JSON.stringify(data));
                }
            })
        }
    })
})

//客户端获取金币数据
router.get('/refreshCoins', (req, res) => {
    const token = req.headers.authorization;
    jwt.verify(token, process.env.SECRETKEY, (err, decoded) => {
        if (err) {
            console.error(err);
            return res.status(401).json({ message: 'Invalid token' });
        } else {
            const sql = 'SELECT coins FROM userdata WHERE user_id = ?';
            db.query(sql, [decoded.user_id], (err, result) => {
                if (err) {
                    console.error(err);
                    res.status(500).send("Database error");
                } else if (result.length > 0) {
                    const Coins = result[0];
                    res.send(JSON.stringify(Coins));
                }
            })
        }
    })
})

//购买物品
router.post('/buyItem', (req, res) => {
    const token = req.headers.authorization;
    jwt.verify(token, process.env.SECRETKEY, (err, decoded) => {
        if (err) {
            console.error(err);
            return res.status(401).json({ message: 'Invalid token' });
        } else {
            const Item = {
                itemId: req.body.itemId,
                itemNum: req.body.itemNum,
            }
            const sql = 'SELECT price FROM item WHERE item_id = ?';
            db.query(sql, [Item.itemId], (err, result) => {
                if (err) {
                    console.error(err);
                    res.status(500).send("Database error");
                } else if (result.length > 0) {
                    const price = result[0].price;
                    const TotalPrice = price * Item.itemNum;
                    //判断金币是否足够
                    const sql_coins = 'SELECT coins FROM userdata WHERE user_id = ?';
                    db.query(sql_coins, [decoded.user_id], (err, result) => {
                        if (err) {
                            console.error(err);
                            res.status(500).send("Database error");
                        } else if (result.length > 0) {
                            const coins = result[0].coins;
                            if (coins >= TotalPrice) {
                                const newCoins = coins - TotalPrice;
                                const sql_update = 'UPDATE userdata SET coins = ? WHERE user_id = ?';
                                db.query(sql_update, [newCoins, decoded.user_id], (err, result) => {
                                    if (err) {
                                        console.error(err);
                                        res.status(500).send("Database error");
                                    } else {
                                        //查询原有的卡牌框数据
                                        const sql_card_frame = 'SELECT card_frame FROM userdata WHERE user_id = ?';
                                        db.query(sql_card_frame, [decoded.user_id], (err, result) => {
                                            if (err) {
                                                console.error(err);
                                                res.status(500).send("Database error");
                                            } else if (result.length > 0) {
                                                let CardFrameData = result[0].card_frame;
                                                if (CardFrameData == null) {
                                                    CardFrameData = { [Item.itemId]: 1 };
                                                } else {
                                                    CardFrameData = JSON.parse(CardFrameData);
                                                    CardFrameData[Item.itemId] = Item.itemNum;
                                                }
                                                const sql_insert = 'UPDATE userdata SET card_frame = ? WHERE user_id = ?';
                                                db.query(sql_insert, [JSON.stringify(CardFrameData), decoded.user_id], (err, result) => {
                                                    if (err) {
                                                        console.error(err);
                                                        res.status(500).send("Database error");
                                                    } else {
                                                        res.send({msg:"购买成功！", coins: newCoins});
                                                    }
                                                })
                                            }
                                        })
                                    }
                                })
                            } else {
                                //金币不足
                                res.send({msg:"金币不足！", coins: coins});
                            }
                        }
                    })
                }
            })
        }
    })
})

//获取拥有的卡套信息
router.get('/getCardFrame', (req, res) => {
    const token = req.headers.authorization;
    jwt.verify(token, process.env.SECRETKEY, (err, decoded) => {
        if (err) {
            console.error(err);
            return res.status(401).json({ message: 'Invalid token' });
        } else {
            const sql = 'SELECT card_frame FROM userdata WHERE user_id = ?'
            db.query(sql, [decoded.user_id], (err, result) => {
                if (err) {
                    console.error(err);
                    res.status(500).send("Database error");
                } else if (result.length > 0) {
                    const CardFrameData = result[0].card_frame;
                    res.send(CardFrameData || {});
                }
            })
        }
    })
})

//获取当前使用中的卡套
router.get('/getCardFrameUsed', async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        const sql = 'SELECT cardframe_used FROM userdata WHERE user_id = ?';
        const result = await GlobalUtil.asyncQuery(sql, [decoded.user_id]);
        if (result.length > 0) {
            const CardFrameUsed = result[0].cardframe_used;
            res.send({msg: CardFrameUsed});
        } else {
            res.status(404).send("User not found");
        }
    } catch (error) {
        console.error(error);
    }
})

//使用卡套
router.post('/setCardFrame', async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        const cardFrameId = req.body;
        let CardFrameName = "";
        //查询卡套名字
        const sql0 = "SELECT item_name FROM item WHERE item_id = ?";
        const result0 = await GlobalUtil.asyncQuery(sql0, cardFrameId);
        if (result0.length > 0) {
            CardFrameName = result0[0].item_name;
        } else {
            res.status(500).send("Database error, no such item");
            return;
        };

        // 查询有没有拥有这个卡套
        const sql = 'SELECT card_frame FROM userdata WHERE user_id = ?';
        const result = await GlobalUtil.asyncQuery(sql, [decoded.user_id]);
        if (result.length > 0) {
            const CardFrameData = JSON.parse(result[0].card_frame);
            let isMatch = false;
            for (const key in CardFrameData) {
                if (Object.prototype.hasOwnProperty.call(CardFrameData, key)) {
                    const element = CardFrameData[key];
                    if (cardFrameId == key && element == 1) {
                        isMatch = true;
                        //查询这个卡套是否使用中
                        const sql1 = "SELECT cardframe_used FROM userdata WHERE user_id = ?"
                        const result1 = await GlobalUtil.asyncQuery(sql1, [decoded.user_id]);
                        if (result1.length > 0) {
                            const cardFrameUsed = result1[0].cardframe_used;
                            if (cardFrameUsed == cardFrameId) {
                                res.send({msg: "正在使用" + CardFrameName + "！", code: 0});
                                return;
                            }
                        }
                        //未在使用情况下，使用并记录这个卡套
                        const sql2 = "UPDATE userdata SET cardframe_used = ? WHERE user_id = ?";
                        const result2 = await GlobalUtil.asyncQuery(sql2, [cardFrameId, decoded.user_id]);
                        res.send({msg: "成功装备" + CardFrameName + "！", code: 1});
                    }
                }
            }
            if (!isMatch) {
                res.send({msg: "尚未拥有" + CardFrameName + "！", code: 0})
            }
        }
    } catch (error) {
        console.error(error);
        res.status(500).send("Database error");
        return;
    }
})

// 修改昵称
router.post('/uploadNickname', async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        const nickname = req.body;
        const sql = 'UPDATE userdata SET nickname = ? WHERE user_id = ?';
        const result = await GlobalUtil.asyncQuery(sql, [nickname, decoded.user_id]);
        res.send({msg: "修改成功！"});
    } catch (error) {
        console.error(error);
        res.status(500).send("Database error");
    }
})

//获取金币排名前50的玩家
router.get('/getCoinTop50', async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        const sql = 'SELECT user_id, nickname, avatar_url, coins FROM userdata ORDER BY coins DESC LIMIT 50';
        const result = await GlobalUtil.asyncQuery(sql, []);
        res.send(result);
    } catch (error) {
        console.error(error);
        res.status(500).send("Database error");
    }
})

// 获取指定user_id用户信息
router.post('/getUserInfoByUserID', async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        const userID = req.body;
        const sql = 'SELECT user_id, nickname, avatar_url, card_frame, designation FROM userdata WHERE user_id = ?';
        const result = await GlobalUtil.asyncQuery(sql, [userID]);
        const timeSql = 'SELECT last_login_time FROM user WHERE user_id = ?';
        const timeResult = await GlobalUtil.asyncQuery(timeSql, [userID]);
        if (timeResult.length > 0) {
            const lastLoginTime = GlobalUtil.formatRelativeTime(timeResult[0].last_login_time);
            result[0].last_login_time = lastLoginTime;
        }
        if (result.length > 0) {
            res.send(result[0]);
        } else {
            res.status(404).send("User not found");
        }
    } catch (error) {
        console.error(error);
        res.status(500).send("Database error");
    }
})

// 用户反馈
router.post('/Feedback', async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        const feedback = req.body;
        const time = GlobalUtil.getDateTime();
        const sql = 'INSERT INTO feedback (user_id, content, time) VALUES (?, ?, ?)';
        const result = await GlobalUtil.asyncQuery(sql, [decoded.user_id, feedback, time]);
        res.send({msg: "反馈成功！"});
    } catch (error) {
        console.error(error);
        res.status(500).send("Database error");
    }
})

//胜利
router.get('/victory', async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        //查询原本拥有的成就
        const sql0 = 'SELECT designation FROM userdata WHERE user_id = ?';
        const result0 = await GlobalUtil.asyncQuery(sql0, [decoded.user_id]);
        let designation;
        if (result0.length > 0) {
                designation = result0[0].designation;
            if (designation == null) {
                designation = {1000: 1};
            } else {
                designation = JSON.parse(designation);
                designation[1000] = 1;
            }
        } else {
            console.error("查询不到用户成就数据");
            res.status(500).send("Database error");
            return;
        }
        const data = JSON.stringify(designation);
        const sql1 = 'UPDATE userdata SET designation = ? WHERE user_id = ?';
        const result1 = await GlobalUtil.asyncQuery(sql1, [data, decoded.user_id]);
        res.send({msg: "胜利！"});
    } catch (error) {
        console.error(error);
        res.status(500).send("Database error");
    }
})

//加金币
router.get('/AddCoin', async (req, res) => {
    try{
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        const sqlGetCoins = 'SELECT coins FROM userdata WHERE user_id = ?';
        const resultGetCoins = await GlobalUtil.asyncQuery(sqlGetCoins, [decoded.user_id]);

        if (resultGetCoins.length > 0) {
            const currentCoins = resultGetCoins[0].coins;
            const newCoins = currentCoins + 1; // 每次消除卡牌增加1金币，可根据需求调整

            // 更新金币数量
            const sqlUpdateCoins = 'UPDATE userdata SET coins = ? WHERE user_id = ?';
            GlobalUtil.asyncQuery(sqlUpdateCoins, [newCoins, decoded.user_id]);
            res.send({msg: "成功获得1金币！"});
        }
    } catch(error) {
        console.error(error);
        res.status(500).send("Database error");
    }
})

//用token免密登录
router.get('/_LoginByToken', async (req, res) => {
    try {
        const token = req.headers.authorization;
        const decoded = await GlobalUtil.asyncVerify(token);
        //更新登录时间
        const LoginTime = GlobalUtil.getDateTime();
        const sql = "UPDATE user SET last_login_time = ? WHERE user_id = ?";
        const result = await GlobalUtil.asyncQuery(sql, [LoginTime, decoded.user_id]);
        res.send({msg: "登陆成功"});
    } catch (error) {
        console.error(error);
        res.status(500).send({ message: 'Invalid token' });
    }
})

module.exports = router;